package com.huluobo.high3videoproject.mvp.live.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.SPUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.huluobo.base.view.BaseActivity;
import com.huluobo.high3videoproject.R;
import com.huluobo.high3videoproject.adapter.ChatMsgAdapter;
import com.huluobo.high3videoproject.adapter.GiftAdapter;
import com.huluobo.high3videoproject.bean.ChatEntity;
import com.huluobo.high3videoproject.bean.GiftBeanResult;
import com.huluobo.high3videoproject.bean.UserMoney;
import com.huluobo.high3videoproject.demo.BezierLineView;
import com.huluobo.high3videoproject.mvp.live.presenter.LiveContract;
import com.huluobo.high3videoproject.mvp.live.presenter.LivePresenter;
import com.huluobo.high3videoproject.net.Constant;
import com.huluobo.high3videoproject.utils.DBUtils;
import com.huluobo.high3videoproject.utils.GlideUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMChatRoomChangeListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMChatRoom;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.controller.DrawHandler;
import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.DanmakuTimer;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import master.flame.danmaku.ui.widget.DanmakuView;

public class LiveActivity extends BaseActivity<LiveContract.View, LivePresenter> implements LiveContract.View,
        View.OnClickListener {

    private DanmakuView danmakuView;
    private EditText et_message;
    private Button btn_sendMessage;
    private DanmakuContext danmakuContext;

    private ConstraintLayout clGift, cl_live;

    private TextView tvMoney, tvPay, tvClose, tvGiftSend, tvGiftName;
    private ImageView ivGiftSelect, gift, ivLike;

    private BezierLineView bezierLineView;

    private RecyclerView rvGift, item_rvRoom;

    private GiftAdapter giftAdapter;

    private GiftBeanResult.GiftBean giftBean;

    private List<GiftBeanResult.GiftBean> giftBeans = new ArrayList<>();

    private ChatMsgAdapter chatMsgAdapter;

    //聊天的数据源
    private List<ChatEntity> chatEntities = new ArrayList<>();

    //接收消息的回调
    private EMMessageListener emMessageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    for (EMMessage msg : messages) {
                        String fromName = msg.getFrom();//拿到消息发送者的用户名
                        EMTextMessageBody messageBody = (EMTextMessageBody) msg.getBody();//EMMessage
                        // 中没办法直接拿到消息内容,需要拿到body转换
                        String content = messageBody.getMessage();
                        //声明一个自己创建的聊天Bean类
                        ChatEntity chatEntity = new ChatEntity(fromName, content);
                        //聊天记录数据源中添加bean类
                        chatEntities.add(chatEntity);
                        //刷新适配器
                        chatMsgAdapter.notifyDataSetChanged();
                        item_rvRoom.scrollToPosition(chatEntities.size() - 1);
                        BaseDanmaku danmaku =
                                danmakuContext.mDanmakuFactory.createDanmaku(DanmakuView.LAYOUT_DIRECTION_RTL);
                        //设置弹幕从右到左
                        danmaku.text = content;
                        danmaku.textColor = Color.BLACK;
                        danmaku.textSize = 40f;
                        danmaku.setTime(2200);
                        danmakuView.addDanmaku(danmaku);
                        danmakuView.start();
                    }
                }
            });
        }
    };

    //接收聊天室状态改变的回调
    private EMChatRoomChangeListener emChatRoomChangeListener = new EMChatRoomChangeListener() {
        @Override
        public void onChatRoomDestroyed(String roomId, String roomName) {

        }

        @Override
        public void onMemberJoined(String roomId, String participant) {
            chatEntities.add(new ChatEntity("系统", participant + "进入聊天室"));
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    chatMsgAdapter.notifyDataSetChanged();
                }
            });
        }

        @Override
        public void onMemberExited(String roomId, String roomName, String participant) {

        }

        @Override
        public void onRemovedFromChatRoom(int reason, String roomId, String roomName, String participant) {

        }

        @Override
        public void onMuteListAdded(String chatRoomId, List<String> mutes, long expireTime) {

        }

        @Override
        public void onMuteListRemoved(String chatRoomId, List<String> mutes) {

        }

        @Override
        public void onWhiteListAdded(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onWhiteListRemoved(String chatRoomId, List<String> whitelist) {

        }

        @Override
        public void onAllMemberMuteStateChanged(String chatRoomId, boolean isMuted) {

        }

        @Override
        public void onAdminAdded(String chatRoomId, String admin) {

        }

        @Override
        public void onAdminRemoved(String chatRoomId, String admin) {

        }

        @Override
        public void onOwnerChanged(String chatRoomId, String newOwner, String oldOwner) {

        }

        @Override
        public void onAnnouncementChanged(String chatRoomId, String announcement) {

        }
    };

    @Override
    protected void initData() {
        presenter = new LivePresenter();
        //演示加载礼物数据,直接加载有可能会报错
        clGift.postDelayed(new Runnable() {
            @Override
            public void run() {
                presenter.getGift();
            }
        }, 400);
        String userName = SPUtils.getInstance().getString(Constant.SP_USERNAME);
        UserMoney userMoney = DBUtils.getInstance().queryUser(userName);
        tvMoney.setText("余额:" + userMoney.getMoney());

        chatEntities.add(new ChatEntity("系统", "禁止涉黄,禁止赌博"));
        chatMsgAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_pay:
                //执行充值的方法
                //正常的逻辑:需要调用支付宝,在支付成功的回调中,往数据库里存入对应的金额
                new AlertDialog.Builder(this)
                        .setTitle("充值")
                        .setMessage("知否给抖音充值100块")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //拿到当前用户,再修改账户的金额
                                String userName = SPUtils.getInstance().getString(Constant.SP_USERNAME);
                                UserMoney userMoney = DBUtils.getInstance().queryUser(userName);
                                String currentMoney = userMoney.getMoney();//拿到当前的余额
                                int newMoney = Integer.parseInt(currentMoney) + 10000;//在当前余额的基础上+10000
                                userMoney.setMoney(String.valueOf(newMoney));//把新的余额赋值给当前余额对象
                                DBUtils.getInstance().updateUser(userMoney);
                                tvMoney.setText("余额:" + newMoney);
                            }
                        })
                        .create()
                        .show();

                break;
            case R.id.tv_close:
                //执行关闭的方法
                closeGiftLayout();
                break;
            case R.id.tv_gift_send:
                //执行发送礼物的方法
                sendGift();
                break;
            case R.id.gift:
                //执行打开礼物页面的方法
                showGiftLayout();
                break;
            case R.id.live_like_iv:
                bezierLineView.addImageVIew();
                break;
            default:
                break;
        }
    }

    //发送礼物的方法
    private void sendGift() {
        closeGiftLayout();
        //创建动画图片组件
        ImageView giftView = new ImageView(this);
        //设置imageView的宽高
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(200, 200);
        giftView.setLayoutParams(layoutParams);
        cl_live.addView(giftView);
        //加载礼物图片到布局上
        GlideUtils.load(this, giftView, giftBean.getGiftpath(), 0, 0, 5);

        //定义礼物动画
        int width = cl_live.getMeasuredWidth();
        int height = cl_live.getMeasuredHeight();

        ObjectAnimator translationX = ObjectAnimator.ofFloat(giftView, "TranslationX", width / 3, 0, width, width / 2);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(giftView, "TranslationY", height / 3, 0, height,
                width / 2);
        ObjectAnimator rotation = ObjectAnimator.ofFloat(giftView, "Rotation", 0, 720);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(giftView, "ScaleX", 1, 3, 2, 1);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(giftView, "ScaleY", 1, 3, 2, 1);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(giftView, "Alpha", 1.0f, 0.1f);


        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(2000);
        animatorSet.setInterpolator(new AccelerateInterpolator());
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha);
        animatorSet.start();

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                cl_live.removeView(giftView);
            }
        });

        //礼物扣款的逻辑,
        //首先要知道发送的是哪个礼物,
        //拿到当前数据库中用户的余额
        //当前余额减去礼物的价格
        //再更新到数据库中,注意,不能new UserMoney,需要去查询获取
        int price = giftBean.getPrice();//礼物的价格
        String money =
                DBUtils.getInstance().queryUser(SPUtils.getInstance().getString(Constant.SP_USERNAME)).getMoney();
        //根据用户名拿到余额
        int newMoney = Integer.parseInt(money) - price;//新余额
        UserMoney userMoney = DBUtils.getInstance().queryUser(SPUtils.getInstance().getString(Constant.SP_USERNAME));
        userMoney.setMoney(String.valueOf(newMoney));
        DBUtils.getInstance().updateUser(userMoney);
        tvMoney.setText("余额:" + newMoney);

        //发送礼物的同时,再聊天室记录中也构建一条消息
        //往聊天数据源中添加一条聊天记录
        chatEntities.add(new ChatEntity(EMClient.getInstance().getCurrentUser(),
                "送出了一个" + giftBean.getGiftname()));
        //让聊天记录滚动到最后一条
        item_rvRoom.scrollToPosition(chatEntities.size() - 1);
        //给聊天室发消息
        sendEMRoomMessage(roomId, "送出了一个" + giftBean.getGiftname());
        //刷新适配器
        chatMsgAdapter.notifyDataSetChanged();
    }

    private void closeGiftLayout() {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_out);
        animation.setDuration(500);
        animation.setInterpolator(new AccelerateInterpolator());
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //隐藏礼物面板
                ivGiftSelect.setImageResource(R.drawable.ic_logo);
                tvGiftName.setText("");
                clGift.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        clGift.startAnimation(animation);
    }

    private void showGiftLayout() {
        clGift.setVisibility(View.VISIBLE);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_in);
        animation.setDuration(500);
        animation.setInterpolator(new AccelerateInterpolator());
        clGift.startAnimation(animation);
    }

    @Override
    protected void initView() {
        danmakuView = findViewById(R.id.danmaView);
        cl_live = findViewById(R.id.cl_live);

        //礼物相关组件
        clGift = findViewById(R.id.cl_gift);
        tvMoney = findViewById(R.id.tv_money);
        tvPay = findViewById(R.id.tv_pay);
        tvClose = findViewById(R.id.tv_close);
        rvGift = findViewById(R.id.rv_gift);
        ivGiftSelect = findViewById(R.id.iv_gift_select);
        tvGiftName = findViewById(R.id.tv_gift_name);
        tvGiftSend = findViewById(R.id.tv_gift_send);
        gift = findViewById(R.id.gift);
        item_rvRoom = findViewById(R.id.item_rvRoom);
        bezierLineView = findViewById(R.id.live_bezier);
        ivLike = findViewById(R.id.live_like_iv);

        //初始化聊天布局
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true);//设置从下往上展示
        item_rvRoom.setLayoutManager(layoutManager);
        chatMsgAdapter = new ChatMsgAdapter(chatEntities);
        item_rvRoom.setAdapter(chatMsgAdapter);

        tvPay.setOnClickListener(this);
        tvClose.setOnClickListener(this);
        tvGiftSend.setOnClickListener(this);
        gift.setOnClickListener(this);
        ivLike.setOnClickListener(this);

        //初始化礼物布局
        rvGift.setLayoutManager(new GridLayoutManager(this, 5));
        giftAdapter = new GiftAdapter(giftBeans);
        rvGift.setAdapter(giftAdapter);

        //设置礼物的点击事件
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                giftBean = giftBeans.get(position);
                GlideUtils.load(LiveActivity.this, ivGiftSelect, giftBean.getGiftpath(), 0, 0, 5);
                tvGiftName.setText(giftBean.getGiftname());
            }
        });

        et_message = findViewById(R.id.ed_danma);
        btn_sendMessage = findViewById(R.id.send);

        //创建弹幕上下文
        danmakuContext = DanmakuContext.create();
        //准备下一条弹幕
        danmakuView.prepare(new BaseDanmakuParser() {
            @Override
            protected IDanmakus parse() {
                return new Danmakus();
            }
        }, danmakuContext);


        danmakuView.setCallback(new DrawHandler.Callback() {
            @Override
            public void prepared() {
                danmakuView.start();
            }

            @Override
            public void updateTimer(DanmakuTimer timer) {

            }

            @Override
            public void danmakuShown(BaseDanmaku danmaku) {

            }

            @Override
            public void drawingFinished() {

            }
        });
        btn_sendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (et_message.getText().length() > 0) {
                    //生成一条弹幕
                    BaseDanmaku danmaku =
                            danmakuContext.mDanmakuFactory.createDanmaku(DanmakuView.LAYOUT_DIRECTION_RTL);//设置弹幕从右到左
                    danmaku.text = et_message.getText().toString();
                    danmaku.textColor = Color.BLACK;
                    danmaku.textSize = 40f;
                    danmaku.setTime(2200);
                    danmakuView.addDanmaku(danmaku);
                    danmakuView.start();

                    //往聊天数据源中添加一条聊天记录
                    chatEntities.add(new ChatEntity(EMClient.getInstance().getCurrentUser(),
                            et_message.getText().toString()));
                    //让聊天记录滚动到最后一条
                    item_rvRoom.scrollToPosition(chatEntities.size() - 1);
                    //给聊天室发消息
                    sendEMRoomMessage(roomId, et_message.getText().toString());
                    et_message.setText("");
                    //刷新适配器
                    chatMsgAdapter.notifyDataSetChanged();

                }
            }
        });
        EMClient.getInstance().chatManager().addMessageListener(emMessageListener);
        EMClient.getInstance().chatroomManager().joinChatRoom(roomId, new EMValueCallBack<EMChatRoom>() {
            @Override
            public void onSuccess(EMChatRoom value) {
                Log.i("TagA,", "加入聊天室成功");
            }

            @Override
            public void onError(int error, String errorMsg) {
                Log.i("TagA,", "加入聊天室失败:" + errorMsg);
            }
        });

        //监听聊天室的事件,如:xxx加入聊天室,xxx退出聊天室

        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(emChatRoomChangeListener);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //离开直播间
        EMClient.getInstance().chatroomManager().leaveChatRoom(roomId);
        //移除消息监听器
        EMClient.getInstance().chatManager().removeMessageListener(emMessageListener);
        //移除聊天室监听器
        EMClient.getInstance().chatroomManager().removeChatRoomListener(emChatRoomChangeListener);
    }

    private String roomId = "224380767502338";

    private void sendEMRoomMessage(String roomId, String content) {
        EMMessage emMessage = EMMessage.createTextSendMessage(content, roomId);
        emMessage.setChatType(EMMessage.ChatType.ChatRoom);
        emMessage.setBody(new EMTextMessageBody(content));
        EMClient.getInstance().chatManager().sendMessage(emMessage);
        emMessage.setMessageStatusCallback(new EMCallBack() {
            @Override
            public void onSuccess() {
                Log.i("TagA", "发送消息成功");
            }

            @Override
            public void onError(int code, String error) {
                Log.i("TagA", "发送消息失败:" + error);
            }
        });
    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_live;
    }

    @Override
    public void onGetGiftSuccess(GiftBeanResult giftBeanResult) {
        if (giftBeanResult.getData().size() > 0) {
            giftBeans.addAll(giftBeanResult.getData());
            giftAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onGetGiftFailed(String error) {

    }
}